<?php
declare (strict_types=1);

namespace app\common\listener;

use app\common\facade\Jpush;
use app\common\model\Relation;
use app\common\model\User;
use app\common\model\UserNotify;
use app\common\tool\account\Account;
use app\common\model\Account as AccountModel;
use think\Exception;
use think\facade\Log;

class VipAward
{
    /**
     */
    public function handle($order)
    {
        try{
            $tier = 1;
            Relation::with('user')->where('new_uid', $order->uid)
                ->field('id,uid,algebra,first_uid')->order('algebra', 'asc')->select()
                ->each(function ($i) use ($order, &$tier){
                    if($i->user->level_id == 2 && $tier <= 2) {//VIP
                        if($tier == 1){
                            $rate = confValue('vip_direct_rate');
                            $cate = AccountModel::VIP_DIRECT;
                            $note = 'VIP直推奖';

                        }else{
                            $rate = confValue('vip_indirect_rate');
                            $cate = AccountModel::VIP_INDIRECT;
                            $note = 'VIP间推奖';
                        }
                        $amount = roundNum($order->vip_profit * $rate, 2);
                        Account::getInstance()->basics($i->uid, 'vip_integ', $amount, $note, '+')->setOrder($order->id)->createBonus($order->uid, $cate);

                        $tier ++;

                        $this->notice($i->user, $i->first_uid, $amount);
                    }
                });
        }catch (\Exception $e){
            Log::write("listener.VipAward:".$e->getMessage());
            throw new Exception("加载失败：".$e->getMessage(), -1);
        }
    }

    /**
     * 通知消息
     * @param $user
     * @param $parent_id
     * @param $amount
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function notice($user, $parent_id, $amount): bool
    {
        $puser = User::where('id', $parent_id)->field('id,registration_id')->find();

        $content = "会员【{$user->nickname}】晋升为VIP，奖励{$amount}VIP积分";
        $parameter = ['event_type'=>1003,'sub_event_type'=>1100];
        $extra = ['extras'=>['parameter'=>json_encode($parameter)]];

        Jpush::sendSingleNotify($puser->registration_id, $content, $extra, $puser->id);

        UserNotify::create([
            'uid' => $parent_id,
            'type' => 7,
            'title' => '晋升为VIP',
            'content' => $content
        ]);

        return true;
    }

}